package os

import (
	"context"
	"os"
	"os/signal"
	"syscall"
)

var SysSignals = []os.Signal{os.Interrupt, os.Kill, syscall.SIGHUP, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGILL, syscall.SIGTRAP, syscall.SIGABRT,
	syscall.SIGBUS, syscall.SIGFPE, syscall.SIGKILL, syscall.SIGSEGV, syscall.SIGPIPE, syscall.SIGALRM, syscall.SIGTERM}

//如果sglcallback返回true则继续监听
func ListenSysSignal(ctx context.Context, sglcallback func(os.Signal) error, sig ...os.Signal) error {
	sigs := make(chan os.Signal, 1)
	signal.Notify(sigs, sig...) //监听所有信号
	ok := true
	var err error
	for ok {
		select {
		case s := <-sigs:
			if er := sglcallback(s); er != nil {
				err = er
				ok = false
			}
		case <-ctx.Done():
			err = ctx.Err()
			ok = false
		}
	}
	signal.Stop(sigs)
	return err
}
